package com.tanklab.signature.common.util;
import java.io.*;
import java.util.*;

public class FileUtil {

    //注意此处的filePath是src开始的相对路径
    public static String getFilePath(String filePath){
        String currentDir = System.getProperty("user.dir");
        return currentDir+"\\"+filePath;
    }

    public static void writeByLine(String filePath, String content) {
        filePath = getFilePath(filePath);
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath, true))) {
            writer.write(content);
            writer.newLine();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //只需输入src开始的相对路径
    public static List<String> readLines(String fsrc) throws IOException {
        fsrc = getFilePath(fsrc);
        try (InputStream in = new FileInputStream(fsrc);
             InputStreamReader inReader = new InputStreamReader(in, "UTF-8");
             // LineNumberReader
             LineNumberReader lineReader = new LineNumberReader(inReader);) {
            String line = "";
            List<String> lines = new ArrayList<String>();
            while (line != null) {
                lines.add(line);
                line = lineReader.readLine();
            }
            return lines;
        }
    }

    public static String findLine(String src,String file){
        List<String> lines=null;
        try{
            lines=readLines(file);
            for(String line : lines)
            {
                if(line.contains(src))return line;//返回符合条件的一行
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        return null;
    }


    public static int countLine(String src,String file,int number){
        List<String> lines=null;
        int count=0;
        try{
            lines=readLines(file);

            for(String line : lines)
            {
                if(line.contains(src)){
                    count++;
                    if(count==number)return 1;
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return 0;
    }

    public static void main(String[] args) {
        writeByLine("src\\elbboot\\src\\main\\java\\com\\neusoft\\elmboot\\config\\userKeyPairs.txt", "This is another sample line.");
    }//src/main/java/com/neusoft/elmboot/config/userKeyPairs.txt
}